<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}物料`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="物料名称" prop="materialName">
        <el-input v-model="drawerProps.row!.materialName" placeholder="请填写物料名称" clearable></el-input>
      </el-form-item>

      <el-form-item label="部件类型" prop="materialType">
        <el-select v-model="drawerProps.row!.materialType" placeholder="请选择部件类型" clearable>
          <el-option v-for="item in materialType" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="MaterialDrawer">
import { ref } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { Material } from "@/api/interface";
import { materialType } from "@/utils/serviceDict";
import axios from "axios";
const baseUrl = import.meta.env.VITE_BASE_URL;
const emit = defineEmits(["refresh"]);
const rules: FormRules = {
  materialId: [{ required: true, message: "请输入物料编号", trigger: "blur" }],
  materialName: [{ required: true, message: "请输入物料名称", trigger: "blur" }],
  materialType: [{ required: true, message: "请选择部件类型", trigger: "change" }]
};

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Material.ResMaterial>;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

function formatDate(date: Date): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，因此需要加1
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
  const userId = Number(userInfo.id) || 0; // 如果没有 id，则使用默认值 0
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      //静态数组新增数据
      if (drawerProps.value.title === "新增") {
        drawerProps.value.row.id = Date.now();
        drawerProps.value.row.createTime = formatDate(new Date());
        const response = await axios.post(baseUrl + "/api/carbon/createMaterial", {
          materialName: drawerProps.value.row.materialName,
          owner: userId,
          materialType: Number(drawerProps.value.row.materialType),
          sourceType: 1
        });
        if (response.data && response.data.code === 200) {
          ElMessage.success("新增内部材料数据成功！");
          emit("refresh"); // 通知父组件刷新
        } else {
          ElMessage.error(response.data.msg || "新增内部材料数据失败");
        }
      }
      //静态数组编辑数据
      else if (drawerProps.value.title === "编辑") {
        const response = await axios.post(baseUrl + "/api/carbon/editMaterial", {
          id: drawerProps.value.row.id, // 编辑时需要传id
          materialName: drawerProps.value.row.materialName,
          owner: userId,
          materialType: Number(drawerProps.value.row.materialType)
        });
        if (response.data && response.data.code === 200) {
          ElMessage.success("更新内部材料数据成功！");
          emit("refresh"); // 通知父组件刷新
        } else {
          ElMessage.error(response.data.msg || "更新内部材料数据失败");
        }
      }
      // 添加以下代码：通知父组件数据已更新
      emit("refresh");
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
